(function () {
  function emitRepaint() {}
  function emitTick() {}
  function emitClick(_x, _y) {}

  // initialize 2d canvas
  var canv = document.createElement("canvas");
  document.body.appendChild(canv);
  canv.style.position = "absolute";
  canv.style.top = canv.style.left = "0";
  var g2d = canv.getContext("2d");

  // call into OCaml bindings
  window.ocamlMain({
    onRepaint: function(f) { emitRepaint = f; },
    onTick: function(f) { emitTick = f; },
    onClick: function(f) { emitClick = f; },

    paintClear: function() {
      g2d.clearRect(0, 0, canv.width, canv.height);
    },

    paintRect: function(x, y, w, h, fill) {
      g2d.fillStyle = fill;
      g2d.fillRect(x, y, w, h);
    },
  });

  // tick events
  window.setInterval(function() { emitTick(); }, 1000);

  // resize events
  function onResize() {
    canv.width = window.innerWidth;
    canv.height = window.innerHeight;
    emitRepaint();
  }
  window.addEventListener("resize", onResize);

  // click events
  function onClick(e) {
    emitClick(e.clientX, e.clientY);
  }
  window.addEventListener("click", onClick);

  // repaint immediately
  onResize();

})();
